package org.aurora.common.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

public abstract class ServiceThread implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(ServiceThread.class);
    private Thread thread = null;
    private final AtomicBoolean isStart = new AtomicBoolean(false);
    private final AtomicBoolean isStop = new AtomicBoolean(false);
    private final String serviceName;
    private final boolean isDaemon;

    public ServiceThread(String serviceName, boolean isDaemon) {
        this.serviceName = serviceName;
        this.isDaemon = isDaemon;
    }

    public ServiceThread(String serviceName) {
        this(serviceName, false);
    }

    public void start() {
        if (isStart.compareAndSet(false, true)) {
            log.info("service thread {} start", serviceName);

            thread = new Thread(this, serviceName);
            thread.setDaemon(isDaemon);
            thread.start();
        }
    }

    public void stop() {
        this.stop(false);
    }

    public void stop(boolean interrupt) {
        if (isStart.get() && isStop.compareAndSet(false, true)) {
            log.info("service thread {} stop", serviceName);
            // 未被启动
            if (!isStart.get()) {
                return;
            }

            if (interrupt && this.thread != null) {
                this.thread.interrupt();
            }
        }
    }

    public boolean isStop() {
        return isStop.get();
    }

}
